package cn.mill.spring;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.AnnotationBeanNameGenerator;

import cn.mill.common.annotation.ServiceDefine;
import cn.mill.core.utils.NormUtil;

/**
 * 
 * @ClassName MillAnnotationBeanNameGenerator
 * @Description spring bean名称 修改类
 * @author nadonghua
 * @date 2019年11月7日 上午11:18:04
 *
 */
public class MillAnnotationBeanNameGenerator extends AnnotationBeanNameGenerator {
	@Override
	public String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) {
		String name = getNameByServiceAnntation(definition, registry);
		if (name != null && !"".equals(name)) {
			return name;
		}
		return super.generateBeanName(definition, registry);
	}
	
	private String getNameByServiceAnntation(BeanDefinition definition, BeanDefinitionRegistry registry) {
		String beanClassName = definition.getBeanClassName();
		try {
			Class<?> aClass = Class.forName(beanClassName);
			ServiceDefine serviceDefine = aClass.getAnnotation(ServiceDefine.class);
			if (serviceDefine == null) {
				return null;
			}
			return NormUtil.isEmpty(serviceDefine.name()) ? "" : serviceDefine.name();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}
}
